<script src="../../common/js/quill-config.js"></script>
<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入部门编号或者名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" :disabled="this.sels.length === 0" @click="grounding">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" :disabled="this.sels.length === 0" @click="offShelf">下架</el-button>
        </el-form-item>

      </el-form>
    </el-col>

    <!--列表v-loading="listLoading"
    :data="pets" -表格数据
    v-loading="listLoading" -> 加载圈
    @selection-change="handleSelectionChange" -> 批量删除
    highlight-current-row  -> 选择一行数据，变亮
    -->

    <el-table :data="pets" v-loading="listLoading"
              @selection-change="handleSelectionChange" highlight-current-row
              style="width: 100%;" :row-key="SpreadPages">
      <!--多选框-->
      <el-table-column type="selection" width="55" :reserve-selection="true">
      </el-table-column>
      <el-table-column type="index" width="70" label="序号">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="120"/>
      <el-table-column prop="costprice" label="成本价" width="80"/>
      <el-table-column prop="saleprice" label="销售价格" width="80"/>
      <el-table-column prop="typeId" label="类型" width="80"/>

      <el-table-column label="宠物封面" width="100">
        <template v-slot="scope">
          <img :src="scope.row.resources.split(',')[0]" height="50"/>
        </template>
      </el-table-column>

      <el-table-column prop="state" label="状态" width="80">
        <template v-slot:="scope">
          <span v-if="scope.row.state == 1" style="color: green">上架</span>
          <span v-else="scope.row.state == 0" style="color: red">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="200"/>
      <el-table-column prop="onsaletime" label="上架时间" width="200"/>
      <el-table-column prop="createtime" label="创建时间" width="200"/>
      <el-table-column prop="username" label="领养人" width="80"/>
      <el-table-column prop="shopName" label="所属店铺" width="100"/>

      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :current-page="currentPage"
                     :page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                     background
                     :total="totals" style="float:right;">
      </el-pagination>
    </el-col>


    <!--添加或修改界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false" @open="handleDialogOpen">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">

        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off" @focus="clearCurrentValidate('name')"/>
        </el-form-item>

        <el-form-item label="成本价">
          <el-input v-model="saveForm.costprice" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="销售价">
          <el-input v-model="saveForm.saleprice" auto-complete="off"/>
        </el-form-item>

        <el-form-item prop="resources" label="宠物图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="店铺">
          <el-select v-model="saveForm.shopId" placeholder="请选择店铺">
            <el-option
                v-for="item in shopList"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="宠物类型">
          <el-cascader
              v-model="saveForm.typeId"
              :options="deptTree"
              :props="{
                    	checkStrictly: true,
                        label: 'name', // 级联框显示那个属性的值
                        value: 'id',    // 回显时需要,回传值的时候也需要
                        emitPath:false,//在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
                    }" clearable>
          </el-cascader>
        </el-form-item>

        <el-form-item label="简介">
          <div class="edit_container">
            <quill-editor v-model="saveForm.intro"
                          :options="editorOptionIntro">
            </quill-editor>
          </div>
        </el-form-item>


        <el-form-item label="领养须知">
          <div class="edit_container">
            <quill-editor v-model="saveForm.adoptNotice"
                          :options="editorOptionAdoptNotice">
            </quill-editor>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  [{header: 1}, {header: 2}], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{list: "ordered"}, {list: "bullet"}], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{script: "sub"}, {script: "super"}], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{indent: "-1"}, {indent: "+1"}], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{direction: "rtl"}], // 文本方向-----[{'direction': 'rtl'}]
  [{size: ["small", false, "large", "huge"]}], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{color: []}, {background: []}], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{font: []}], // 字体种类-----[{ font: [] }]
  [{align: []}], // 对齐方式-----[{ align: [] }]
  ["clean"], // 清除文本格式-----['clean']
  ["image", "link"] // 链接、图片、视频-----['link', 'image', 'video']
];
import quillConfig from "../../common/js/quill-config";
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      //1.分页查询相关数据
      totals: 0,//总记录条数
      currentPage: 1,//当前页,要传递到后台的
      pageSize: 5, //每页显示多少条
      pets: [], //当前页数据

      listLoading: false, //加载圈

      title: '',

      //2.高级查询相关数据
      keyword: '',
      //4.批量删除相关数据
      sels: [], //存储多选记录

      //5.添加和修改相关数据
      saveFormVisible: false,


      deptTree: [], //部门树
      shopList: [],//查询所以店铺
      imgUrls:[],      //宠物图片地址数组

      //文件上传相关数据
      fileList: [],

      saveForm: {
        id: null,
        name: "青秀",
        costprice: 11,
        saleprice: 22.22,
        typeId: 19,
        resources: 'http://60.204.187.34:8800/group1/M00/00/08/wKgAcGZNyjqAFkyvAAWN2sjz6Y8415.gif',
        state: 1,
        intro:'', //简介
        adoptNotice:'',//领养须知
        shopId: null,
        userId: null,
      },
      //添加和修改校验规则-表单项校验
      saveFormRules: {
        name: [
          {required: true, message: '请输入部门名称', trigger: 'blur'}
        ],
        managerUserName: [
          {required: true, message: '请选择部门管理员', trigger: 'blur'}
        ],
        parentName: [
          {required: true, message: '请选择上级部门', trigger: 'blur'}
        ],

      },
      //富文本编辑器配置
      editorOptionAdoptNotice: quillConfig,
      //     {
      //   modules: {
      //     //工具栏定义的
      //     toolbar: toolbarOptions
      //   },
      //   //主题
      //   theme: "snow",
      //   placeholder: "请开始书写您的领养须知内容..."
      // },
      editorOptionIntro: quillConfig,
      //     {
      //   modules: {
      //     //工具栏定义的
      //     toolbar: toolbarOptions
      //   },
      //   //主题
      //   theme: "snow",
      //   placeholder: "请开始书写您的简介内容..."
      // },


    }
  },
  methods: {

    //上架
    grounding() {
      let ids = this.sels.map(obj => obj.id)//获取id
      if (ids.length != 0 || this.sels != null) {
        this.listLoading = true
        this.$http.patch("/pet/grounding", ids).then(res => {
          this.listLoading = false
          if (res.data.success) {
            this.sels = []
            this.$message.success("上架申请成功，正在等待审核...")
          } else {
            this.$message.error(res.data.message)
          }
          this.getTableData()
        })
      } else {
        alert("老铁，你不选中数据，臣妾上架不了啊....")
      }
    },
    //下架
    offShelf() {
      let ids = this.sels.map(obj => obj.id)//获取id
      if (ids.length != 0 || this.sels != null) {
        this.listLoading = true
        this.$http.patch("/pet/offShelf", ids).then(res => {
          this.listLoading = false
          if (res.data.success) {
            this.sels = []
            this.$message.success("下架申请成功")
          } else {
            this.$message.error(res.data.message)
          }
          this.getTableData()
        })
      } else {
        alert("老铁，你不选中数据，臣妾下架不了啊....")
      }
    },

    //获取宠物类型树 - 无线级联
    getDeptTree() {
      this.$http.get("/petType/deptTree").then(res => {
        this.deptTree = res.data;
      })
    },
    //跨页操作
    SpreadPages(row) {
      return row.id
    },
    //1.分页查询相关方法
    //1.1.获取列表数据
    getTableData() {
      this.listLoading = true //开启加载圈
      var params = {
        "currentPage": this.currentPage, //点击的当前第几页
        "pageSize": this.pageSize,   //当前页需要显示多少条数据
        "keyword": this.keyword    //模糊查询 ->关键字
      }
      this.$http.post("/pet", params).then(request => {
        //接收参数添加到表格中(pets),request.data ->固定写法
        this.pets = request.data.list
        this.totals = request.data.totals
        this.listLoading = false //关闭加载圈
      })
    },
    //1.2.选择第几页时触发
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage //1 -> 2
      this.getTableData()
    },
    //1.3.选择每页显示记录条数时触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getTableData()
    },

    //2.高级查询相关方法
    keywordQuery() {
      this.currentPage = 1; //从第一页开始查询
      this.getTableData();
    },

    //3.删除相关方法
    //row -> 当前行对象 获取一行数据
    handleDel(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/pet/" + row.id,).then(res => {
          if (res.data.success) {
            //处理当前页->算总页数 Math.ceil() (向上取整，往最大了取值)
            let totalPage = Math.ceil(this.totals / this.pageSize);
            //当删除最后一页的最后一条数据，并且不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message.success("操作删除成功")
            this.getTableData()
          } else {
            this.$message.error(res.data.message + "删除失败")
          }
        }).catch(res => {
          this.$message.error("网络异常，请查看您的网络")
        })
      }).catch(() => {
        this.$message.error("已取消删除")
      });
    },

    //4.批量删除相关方法
    //4.1.选项改变时触发
    handleSelectionChange(val) {
      this.sels = val
    },
    //4.2.批量删除
    handlePatchDel() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = this.sels.map(obj => obj.id)//获取批量删除对象的id，组成数组。
        this.$http.patch("/pet", ids).then(res => {
          if (res.data.success) {
            //计算总页数  Math.ceil() (向上取整，往最大了取值) Math.floor() (向下取整，往最小了取值)
            if (ids.length >= this.pets.length && this.currentPage !== 1) { //页数合理化
              let number = Math.ceil(this.totals / this.pageSize) - (Math.floor((ids.length - this.totals % this.pageSize) / this.pageSize) + 1);
              if (number < this.currentPage) {
                this.currentPage = number
              }
            }
            this.sels = []
            this.$message.success("操作批量删除成功")
            this.getTableData()
          } else {
            this.$message.error("服务器异常，批量删除失败")
          }
        }).catch(res => {
          this.$message.error("网络异常，请查看您的网络")
        })
      }).catch(() => {
        this.$message.error("已取消批量删除")
      });
    },
    //5.添加和修改相关方法
    //5.1.点击添加弹出对话框
    handleAdd() {
      this.title = "添加数据"
      this.saveFormVisible = true //打开模态框
      this.saveForm = {
        id: null,
        name: "青秀",
        costprice: 11,
        saleprice: 22.22,
        typeId: null,
        resources: 'http://60.204.187.34:8800/group1/M00/00/08/wKgAcGZNyjqAFkyvAAWN2sjz6Y8415.gif',
        state: 1,
        intro:'', //简介
        adoptNotice:'',//领养须知
        shopId: null,
        userId: null,
      }
      this.fileList = []//清空存储图片文件
      this.imgUrls = [] //清空宠物图片地址数组
      this.getShop()
      this.getDeptTree()
    },
    //5.2.点击修改弹出对话框
    handleEdit(row) {
      this.title = "编辑数据"
      this.saveFormVisible = true //打开模态框
      this.saveForm = Object.assign({}, row)
      this.fileList = []//清空存储图片文件
     // this.imgUrls = [] //清空宠物图片地址数组
      this.$http.get("/pet/getResources/" + row.id).then(res=>{
        var urls = res.data.split(",")
        urls.forEach(img =>{
          this.fileList.push({
            url: img
          })
        })

      })
      // if (this.saveForm.resources) {
      //   this.fileList.push({'url': this.saveForm.resources})
      // }
      this.getShop()
      this.getDeptTree()
    },
    //5.3.提交表单数据操作数据库
    saveSubmit() {
      //所有表单项校验通过才能提交，只要员工表单项校验不通过就不能提交，-所有表单项校验通过返回true
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          let para = Object.assign({},this.saveForm)

          para.imgUrls = this.imgUrls;
          if (para.imgUrls != null && para.imgUrls.length >0){
            //展示第一张图片
            para.resources = this.imgUrls[0];
          }

          this.$http.put("/pet",this.saveForm).then(res => {
            if (res.data.success) {
              this.$message.success("操作" + this.title + "成功")
              this.getTableData()
              this.saveFormVisible = false
            } else {
              this.$message.error(res.data.message + ',' + this.title + "未成功")
              this.saveFormVisible = false
            }
          }).catch(res => {
            this.$message.error("网络异常，请查看您的网络")
          })
        } else {
          this.$message.error("您有必须填写的数据未填写")
        }
      })
    },

    //文件图片上传的业务逻辑
    handleSuccess(response, file, fileList) {
      //this.saveForm.resources = "http://60.204.187.34:8800" + response.obj;
      this.imgUrls.push("http://60.204.187.34:8800" + response.obj);
    },
    //文件图片删除的业务逻辑
    handleRemove(file, fileList) {
      var filePath = file.response.obj;
      this.$http.delete("/fastDfs/?path=" + filePath)
          .then(res => {
            if (res.data.success) {
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
            } else {
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
    },
    //1.表单弹出时：清除校验规则
    handleDialogOpen() {
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
    //2.获得焦点清除当前校验
    clearCurrentValidate(field) {
      this.$refs.saveForm.clearValidate(field);
    },
    getShop() {
      this.$http.get("/shop").then(res => {
        this.shopList = res.data
      })
    },

  },
  mounted() {
    this.getTableData();
  }
}

</script>

<style scoped></style>
